/**
 * 该文件抛出以下方法：
 * 1. 根据low-code组件与配置生成筛选组件
 * 2. 提供筛选组件的事件处理方法
 * 3. 提供筛选结果获取方法
 */

import LowCodeItem from '@/components/low-code/LowCodeItem'
import type { FormItemDto } from '@/components/low-code/types'
import { Col, Row } from 'ant-design-vue'
import { Component } from 'vue-facing-decorator'
import Render from '@/render/Render'

export interface FilterDto {
    [key: string]: FormItemDto
}
@Component
export default class FilterRender extends Render {
    filters = {} as FilterDto
    // 不要padding
    noFilterPadding = false

    filterTheme = 'dark'

    // 由于回调this指向问题，需要在方法中赋值filter配置
    filterConfig() {
        return {} as FilterDto
    }

    // 重置筛选条件
    resetfilters() {
        Object.keys(this.filters).forEach((key: string) => {
            if (['buttonGroup', 'button'].includes(this.filters[key]['element'])) return
            this.filters[key].readonly || (this.filters[key].value = '')
        })
    }

    // 获取筛选结果
    getFilters() {
        const params = {} as { [key: string]: any }
        Object.keys(this.filters).forEach((key: string) => {
            if (['buttonGroup', 'button'].includes(this.filters[key].element)) return
            if (['', undefined].includes(this.filters[key].value as string)) return
            if (this.filters[key]?.params?.arrayToNumber) {
                const values = this.filters[key].value as number[] | string[]
                params[key] = values[values.length - 1]
            } else {
                params[key] = this.filters[key].value
            }
        })
        return params
    }

    onMounted() {
        // 初始化筛选条件
        this.filters = this.filterConfig()
    }

    renderFilter() {
        const filterEls = Object.keys(this.filters).map(key => {
            const item = this.filters[key]
            if (item.hidden) return ''
            if (!item.prefix) item.prefix = <span class="text-black-300 mr-8">{item.name}</span>
            return <Col md={item.span || 6} class={(item.colClass || '')} span={item.span || 6}>
                <div class={'filter-item !flex items-center py-6 text-sm rounded-sm mb-12 ' + (['button', 'buttonGroup'].includes(item.element) && 'btn')}>
                    { LowCodeItem(item) }
                </div>
            </Col>
        })
        return <div class={`${this.noFilterPadding ? '' : 'px-20px pt-20px'}`}>
            <Row gutter={20}>
                {filterEls}
            </Row>
        </div>
    }
}